//
//  DocInfoViewController.m
//  安好
//
//  Created by lianchuang on 14/11/13.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "DocInfoViewController.h"
#import "ConsultDocListCell.h"
#import "DocHospViewCell.h"
#import "ExpertViewCell.h"
#import "DocCommentCell.h"
#import "UILabel+Create.h"
#import "DocFootView.h"
#import "sys/utsname.h"
#import "ConsultViewController.h"
#import "YXJSON.h"
#import "DocCommentViewController.h"
#import "PopoverView.h"
#import "DocCommentListViewController.h"
#import "SpecifyDoctorManager.h"
#import "ReportViewController.h"
#import "ReportViewController.h"
#import "LoginViewController.h"
@interface DocInfoViewController ()<DoctorInfoDelegate,UIAlertViewDelegate>

@end

@implementation DocInfoViewController
{
    NSArray *titles;
    NSArray *images;
    NSArray *selectArray;
    PopoverView *pop;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.edgesForExtendedLayout=UIRectEdgeNone;

    titles = @[@"设为指定医生",@"分享", @"投诉医生"];
    images = @[@"附近_医生",@"百科_分享", @"医生_投诉"];
    selectArray=@[@"附近_已认证",@"百科_分享成功",@"医生_投诉成功"];
    self.tableview.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
    self.tableview.dataSource=self;
    self.tableview.delegate=self;
    self.tableview.hidden=YES;
    self.tableview.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    
    if (kScreenWidth==414) {
        self.footView=[[[NSBundle mainBundle]loadNibNamed:@"DocFootView" owner:self options:nil] lastObject];
    }else
    {
        self.footView=[[[NSBundle mainBundle]loadNibNamed:@"DocFootView" owner:self options:nil] objectAtIndex:0];
    }
    self.footView.docDelegate=self;
    self.tableview.tableFooterView=self.footView;
    
    self.docInfo=[[NSDictionary alloc]init];
    UIBarButtonItem *backImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    backImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backImg;
    
    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
    [rightButton setImage:[UIImage imageNamed:@"公用_筛选.png"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDocInfo];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [pop dismiss:YES];
    [self hiddenLabel];
}
/**
 *  请求医生详情
 */
#pragma mark 请求医生详情数据
- (void)loadDocInfo
{
    [self showActionView];
    
    NSString *getURL=[NSString stringWithFormat:@"%@docuser/detail/?version=%@&platform=%@&doctoruid=%@",kBaseURL,kVersion,kPlatform,self.doctoruid];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:getURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("%@", responseObject);
        self.tableview.hidden=NO;
        [self hiddenActionView];
        NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
        if ([status isEqualToString:@"1"]) {
            self.docInfo=[responseObject valueForKey:@"data"];
            self.navigationItem.title=[self.docInfo valueForKey:@"username"];
            NSString *apoint=[NSString stringWithFormat:@"%@",[self.docInfo valueForKey:@"isappoint"]];

            if ([apoint isEqualToString:@"0"]) {
                titles = @[@"设为指定医生",@"分享", @"投诉医生"];
                images = @[@"附近_医生",@"百科_分享", @"医生_投诉"];

            }else
            {
                titles = @[@"已为指定医生",@"分享", @"投诉医生"];
                images = @[@"附近_已认证",@"百科_分享", @"医生_投诉"];
            }
            NSString *follow=[NSString stringWithFormat:@"%@",[self.docInfo valueForKey:@"isfollow"]];
            if ([follow isEqualToString:@"0"]) {
                [self.footView.focusBttuon setTitle:@"关注" forState:UIControlStateNormal];
            }else
            {
                [self.footView.focusBttuon setTitle:@"已关注" forState:UIControlStateNormal];
            }
            [self.tableview reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("%@", operation);
        [self hiddenActionView];
        [self shouLabel:@"暂无数据"];
    }];
}

-(void)AFNetGETForDocInfo
{
    [self showActionView];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString * getUrl = [NSString stringWithFormat:@"%@docuser/detail/" ,kBaseURL];
    NSDictionary * parametersDic = @{@"":kVersion,@"":kPlatform,@"doctoruid":self.doctoruid};

    [manager GET:getUrl parameters:parametersDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hiddenActionView];
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            
            alertContent([responseObject objectForKey:@"msg"]);
        }
        else
        {
            self.docInfo = responseObject[@"data"];
            self.navigationItem.title=[self.docInfo valueForKey:@"username"];
             [self.tableview reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("失败");
        [self hiddenActionView];
        
    }];
}




#pragma mark UITableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }else if (section==1)
    {
        return 1;
    }else if (section==2)
    {
        return 2;
    }
    else return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        static NSString *Indentifier=@"consultdocList";
        ConsultDocListCell *cell=[tableView dequeueReusableCellWithIdentifier:Indentifier];
        if (!cell) {
            if (kScreenWidth==414) {
                cell=[[[NSBundle mainBundle]loadNibNamed:@"ConsultDocListCell" owner:self options:nil] lastObject];
            }else
            {
                cell=[[[NSBundle mainBundle]loadNibNamed:@"ConsultDocListCell" owner:self options:nil] objectAtIndex:0];
            }
        }
        [cell.docImage setImageWithURL:[NSURL URLWithString:[self.docInfo valueForKey:@"avatar"]] placeholderImage:nil];
        cell.docImage.layer.cornerRadius=3.0;
        cell.docImage.layer.masksToBounds=YES;
        
        cell.docName.text=[self.docInfo valueForKey:@"username"];
        cell.docHospital.text=[NSString stringWithFormat:@"科室：%@",[self.docInfo valueForKey:@"departmentname"]];
        cell.onlineStatus.hidden=YES;
        cell.onlineImage.hidden=YES;
        cell.docExpert.text=[NSString stringWithFormat:@"职称：%@",[self.docInfo valueForKey:@"doclevel"]];
        cell.docGood.text=[NSString stringWithFormat:@"赞（%@）",[self.docInfo valueForKey:@"good"]];
        cell.peerAuthor.text=[NSString stringWithFormat:@"同行认证（%@）",[self.docInfo valueForKey:@"agree"]];
        cell.docFans.text=[NSString stringWithFormat:@"粉丝（%@）",[self.docInfo valueForKey:@"fans"]];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
 
        return cell;
    }
    else if (indexPath.section==1)
    {
        static NSString *Indentifier=@"hosp";
        DocHospViewCell *cell=[tableView dequeueReusableCellWithIdentifier:Indentifier];
        if (!cell) {
            if (kScreenWidth==414) {
                cell=[[[NSBundle mainBundle]loadNibNamed:@"DocHospViewCell" owner:self options:nil] lastObject];
            }else{
                cell=[[[NSBundle mainBundle]loadNibNamed:@"DocHospViewCell" owner:self options:nil] objectAtIndex:0];
            }
        }
        cell.docHosptal.text=[self.docInfo valueForKey:@"hospitalname"];
        NSString *hoslev=[NSString stringWithFormat:@"%@",[self.docInfo valueForKey:@"hoslevel"]];
        
        cell.hospLevel.text=hoslev;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;

        return cell;
    }else if (indexPath.section==2){
        static NSString *Indentifier=@"expert";
        ExpertViewCell *cell=[tableView dequeueReusableCellWithIdentifier:Indentifier];
        if (!cell) {
            if (kScreenWidth==414) {
                 cell=[[[NSBundle mainBundle]loadNibNamed:@"ExpertViewCell" owner:self options:nil] lastObject];
            }else
            {
                 cell=[[[NSBundle mainBundle]loadNibNamed:@"ExpertViewCell" owner:self options:nil] objectAtIndex:0];
            }
        }
        if (indexPath.row==0) {
            cell.itemTitle.text=@"擅长";
            cell.itemContent.numberOfLines=1;
            cell.itemContent.frame=CGRectMake(65,IPhone6Plus?18: 14, kScreenWidth-65-15, IPhone6Plus?18:15);
            cell.itemContent.text=[self.docInfo valueForKey:@"expertise"];
        }else
        {
            cell.itemTitle.text=@"简介";
            cell.itemContent.numberOfLines=0;
            cell.itemContent.text=[self.docInfo valueForKey:@"bio"];
            
            if (cell.itemContent.text.length>0) {
                NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:cell.itemContent.text];
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                [paragraphStyle setLineSpacing:5];//调整行间距
                [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [cell.itemContent.text length])];
                paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
                cell.itemContent.attributedText = attributedString;
                [cell.itemContent sizeToFit];
            }
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }else
    {
        static NSString *Indentifier=@"comment";
        DocCommentCell *cell=[tableView dequeueReusableCellWithIdentifier:Indentifier];
        if (!cell) {
            if (kScreenWidth==414) {
                cell=[[[NSBundle mainBundle]loadNibNamed:@"DocCommentCell" owner:self options:nil] lastObject];
            }else{
                cell=[[[NSBundle mainBundle]loadNibNamed:@"DocCommentCell" owner:self options:nil] objectAtIndex:0];
            }
        }
        cell.itemTitle.text=@"用户评价";
        cell.itemCount.text=[NSString stringWithFormat:@"%@个",[self.docInfo valueForKey:@"score_count"]];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;

        return cell;
    }
}
#pragma mark UITableviewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==3) {
//        DocCommentViewController *docComment=[[DocCommentViewController alloc]initWithNibName:@"DocCommentViewController" bundle:[NSBundle mainBundle]];
//        docComment.doctoruid=self.doctoruid;
//        docComment.isFromDoc=YES;
//        [self.navigationController pushViewController:docComment animated:YES];
        DocCommentListViewController *commentList=[[DocCommentListViewController alloc]initWithNibName:@"DocCommentListViewController" bundle:[NSBundle mainBundle]];
        commentList.doctoruid=self.doctoruid;
        commentList.isFromDoc=YES;
        [self.navigationController pushViewController:commentList animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        if (kScreenWidth==414) {
            return 156.0f;
        }
        return 130;
    }else if (indexPath.section==2)
    {
        if (indexPath.row==0) {
            if (kScreenWidth==414) {
                return 53;
            }
            return 44;
        }else
        {
            ExpertViewCell *cell=(ExpertViewCell *)[self tableView:self.tableview cellForRowAtIndexPath:indexPath];
            return cell.itemContent.frame.size.height+(IPhone6Plus?36:30);
        }
    }else
    {
        if (kScreenWidth==414) {
            return 53;
        }
        return 44;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 0;
    }
    else return 10;
}


#pragma mark DocDelegate
- (void)setConsultDoc
{
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    NSString * name= userModel.username;
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    NSString *mobile_certification=[NSString stringWithFormat:@"%@",[userdefault valueForKey:@"authentication"]];
    if (name.length>0&&[mobile_certification isEqualToString:@"1"]) {
        NSString *isallow=[NSString stringWithFormat:@"%@",[self.docInfo valueForKey:@"isallow"]];
        if (![isallow isEqualToString:@"1"]) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"该医生不在咨询时间范围内，设为指定医生，可能无法及时的回复您的咨询问题！" delegate:self cancelButtonTitle:@"继续咨询" otherButtonTitles:@"取消", nil];
            [alert show];
        }else{
            [self setConsultWithDocInfo];
        }
    }
    else if (name.length>0&&[mobile_certification isEqualToString:@"0"])
    {
        LoginViewController * loginViewController = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
        [self presentViewController:loginViewController animated:YES completion:^{
        }];
        loginViewController.realName.isFromRegist=NO;
        [loginViewController showRealNameView];
    }
}
- (void)focusDoc:(UIButton *)sender
{
    if([sender.titleLabel.text isEqualToString:@"关注"])
    {
        [self addfocuse];
    }
    else if ([sender.titleLabel.text isEqualToString:@"已关注"])
    {
        [self cancelFocuse];
    }
}
- (void)addfocuse
{
    NSString * requestURL = [NSString stringWithFormat:@"%@user/followdoctor/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,
                                 @"version":kVersion,
                                 @"doctoruid":self.doctoruid,
                                 };
    [manager POST:requestURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *status=[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"status"]];
        if ([status isEqualToString:@"1"]) {
             [self showCustomHudSingleLine:@"关注成功"];
            [self.footView.focusBttuon setTitle:@"已关注" forState:UIControlStateNormal];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
- (void)cancelFocuse
{
    NSString * requestURL = [NSString stringWithFormat:@"%@user/unfollowdoctor/",kBaseURL];
//    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
//    NSString *myuid=userModel.uid;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,
                                 @"version":kVersion,
                                 @"doctoruid":self.doctoruid,
                                 };
    [manager POST:requestURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *status=[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"status"]];
        if ([status isEqualToString:@"1"]) {
             [self showCustomHudSingleLine:@"取消关注"];
            [self.footView.focusBttuon setTitle:@"关注" forState:UIControlStateNormal];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
#pragma mark 返回上一层和更多
- (void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)rightButtonClicked:(UIButton *)sender
{
    CGPoint point = CGPointMake(sender.frame.origin.x + sender.frame.size.width/2, 64);
    pop = [[PopoverView alloc] initWithPoint:point titles:titles images:images selectImage:selectArray];
    pop.selectRowAtIndex = ^(NSInteger index){
        MyNSLog("select index:%d", index);
        switch (index) {
            case 0:
            {
                NSString *follow=self.footView.focusBttuon.titleLabel.text;
                //判断是否关注
                if ([follow isEqualToString:@"已关注"]) {
                    //判断是否已是指定医生
                    NSString *apoint=[titles objectAtIndex:0];
                    
                    if ([apoint isEqualToString:@"设为指定医生"]) {
                        [self attention];
                    }else
                    {
                        [self unattention];
                    }
                }else
                {
                     [self showCustomHudSingleLine:@"请先关注"];
                }
            }
                break;
            case 1:
            {
                [self showShareView];
            }
                break;
            case 2:
            {
                ReportViewController *report=[[ReportViewController alloc]initWithNibName:@"ReportViewController" bundle:[NSBundle mainBundle]];
                report.objectids=self.doctoruid;
                report.reportType=0;
                report.isFromDocDetail=YES;
                [self.navigationController pushViewController:report animated:YES];
            }
                break;
            default:
                break;
        }
    };
    [pop show];

}
- (void)attention
{
    NSString * requestURL = [NSString stringWithFormat:@"%@question/addappoint/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,
                                 @"version":kVersion,
                                 @"doctoruid":self.doctoruid,
                                 @"doctorname":[self.docInfo valueForKey:@"username"],
                                 @"doclevelid":[self.docInfo valueForKey:@"doclevelid"],
                                 @"departmentid":[self.docInfo valueForKey:@"departmentid"],
                                 @"departmentname":[self.docInfo valueForKey:@"departmentname"],
                                 };
    [manager POST:requestURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *status=[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSDictionary *dic=@{
                                @"doctoruid":self.doctoruid,
                                @"doctorname":[self.docInfo valueForKey:@"username"],
                                @"doclevelid":[self.docInfo valueForKey:@"doclevelid"],
                                @"departmentid":[self.docInfo valueForKey:@"departmentid"],
                                @"departmentname":[self.docInfo valueForKey:@"departmentname"],
                                @"avatar":[self.docInfo valueForKey:@"avatar"],
                                };
            [[SpecifyDoctorManager instance] insertSpecifyDoctorToDB:dic];
            titles = @[@"已为指定医生",@"分享", @"投诉医生"];
            images = @[@"附近_已认证",@"百科_分享", @"医生_投诉"];
            [self showCustomHudSingleLine:@"已设为指定医生"];

        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
- (void)unattention
{
    NSString * requestURL = [NSString stringWithFormat:@"%@question/delappoint/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,
                                 @"version":kVersion,
                                 @"doctoruid":self.doctoruid,
                                 };
    [manager POST:requestURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *status=[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"status"]];
        if ([status isEqualToString:@"1"]) {
            [self showCustomHudSingleLine:@"取消指定医生"];

            [[SpecifyDoctorManager instance] deleteSpecifyDoctorFromDBWithDoctoruid:self.doctoruid];
            titles = @[@"设为指定医生",@"分享", @"投诉医生"];
            images = @[@"附近_医生",@"百科_分享", @"医生_投诉"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

}
#pragma 实现share方法，通过点击的视图的tag值判断是什么类型的分享
- (void)share:(UITapGestureRecognizer *)shareTap{
    NSString * url= [NSString stringWithFormat:@"http://m.niruoanhao.com/share/docuser/%@",self.doctoruid];
    NSString * title = @"你若安好，便是晴天";
    NSString * text = @"找对医生看对病，提供全国近四十万执业医生简介、擅长专业";
    UIImage * image = [UIImage imageNamed:@"二维码"];
    switch (shareTap.view.tag) {
        case 11:{//微信
            [self weixinShare:url :title :text :image];
        }
            break;
        case 12:{//朋友圈
            [self weixinFriendShare:url :title :text :image];
        }
            break;
        case 13:{//短信
            [self showSMSPicker:url :title :text :nil];
        }
            break;
        case 14:{//QQ
            [self qqShare:url :title :text :image];
        }
            break;
        case 15:{//QQ空间
            [self qqZoneShare:url :title :text :image];
        }
            break;
        case 16:{//新浪微博
            [self sinaWeiboShare:url :title :text :image];
        }
            break;
            
        default:
            break;
    }
}
- (void)setConsultWithDocInfo
{
    if (self.isFromConsult) {
        if (self.docDelegate&&[self.docDelegate respondsToSelector:@selector(returnDocInfo:)]) {
            [self.docDelegate returnDocInfo:self.docInfo];
        }
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[ConsultViewController class]]) {
                ConsultViewController *consult=(ConsultViewController *)controller;
                consult.docInfo=self.docInfo;
                //            self.docDelegate=consult;
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    }else
    {
        ConsultViewController *consult=[[ConsultViewController alloc]initWithNibName:@"ConsultViewController" bundle:[NSBundle mainBundle]];
        consult.docInfo=self.docInfo;
        [self.navigationController pushViewController:consult animated:YES];
    }
}
#pragma mark UIALertdelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            [self setConsultWithDocInfo];
        }
            break;
            
        default:
            break;
    }
}
@end
